#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>

int file_size(char* filename)
{
    struct stat statbuf;
    stat(filename,&statbuf);
    int size = statbuf.st_size;

    return size;
}

/******************************************************************
Main Function
******************************************************************/
int main(int argc, char* argv[])
{
	int FileNum = 0, i = 0, j = 0, size = 0, rnum = 0, wsize,bufsize;
	FILE *OutFd, *InFd;
	char   param[64] = {0};
	char *File[20], *buf = NULL;
	
	if (argc < 3)
	{
		printf("Input arg err %d < 4\r\n", argc);
		return -1;
	}

	FileNum = strtol(argv[2], NULL, 10);

	if (argc < (FileNum + 3))
	{
		printf("Input arg err %d < %d \r\n", argc, (FileNum + 2));
		return -1;
	}

	OutFd = fopen(argv[1], "wb+");
	for (i = 0; i < FileNum; i++)
	{
			File[i] = argv[i + 3];
			InFd = fopen(File[i], "rb");
			if (NULL == InFd)
			{
				printf("Open file err %s", File[i]);
				fclose(OutFd);
				return -1;
			}

			size = file_size(File[i]);
			buf = (char *)calloc(1, size);
			if (NULL == buf)
			{
				printf("calloc Fail");
				fclose(OutFd);
				return -1;
			}

			rnum = fread(buf, 1, size, InFd);
			if (rnum != size)
			{
				printf("read %d %d file %d", rnum, size, i);
				fclose(OutFd);
				free(buf);
				return -1;
			}

			printf("write %s size %d\r\n", File[i], size);
			wsize = fwrite(buf, 1, size, OutFd);
			if (wsize != size)
			{
				printf("write %d %d file %d", wsize, size, i);
				fclose(OutFd);
				free(buf);
				return -1;
			}

			printf("write end\r\n");
			free(buf);
	}

	/* 1:num 4:size 30:name */
	bufsize = (1 + 34 * FileNum);
	buf = (char *)calloc(1, size);
	buf[bufsize - 1] = (char)FileNum;
	
	for (i = 0; i < FileNum; i++)
	{
			size = file_size(File[i]);
			for (j = 0; j < 4; j++)
			{
				buf[30 * FileNum + i * 4 + 3 - j] = (char)(size >> ((3 - j) * 8));  
			}

			for (j = strlen(File[i]) - 1; j > 0 ; j--)
			{
				if ('/' == File[i][j])
				{
					j = j + 1;
					break;
				}
			}

			printf("file %s\r\n", &File[i][j]);
			strncpy(&buf[30 * i], &File[i][j], strlen(&File[i][j]));
	}

	wsize = fwrite(buf, 1, bufsize, OutFd);
	if (wsize != bufsize)
	{
		printf("write %d %d", wsize, bufsize);
		fclose(OutFd);
		free(buf);
		return -1;
	}

	fclose(OutFd);
	free(buf);

	snprintf(param, sizeof(param), "chmod 777 %s", argv[1]);
	system(param);
	
	return 0;
}


